// Copyright 2018 The ksonnet authors
//
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package actions

import (
	"bytes"
	"testing"

	amocks "github.com/ksonnet/ksonnet/pkg/app/mocks"
	"github.com/ksonnet/ksonnet/pkg/component"
	cmocks "github.com/ksonnet/ksonnet/pkg/component/mocks"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/require"
)

func TestModuleList(t *testing.T) {
	validComponentManager := func(appMock *amocks.App) component.Manager {
		cm := &cmocks.Manager{}

		modules := []component.Module{
			mockNsWithName("b"),
			mockNsWithName("a"),
		}
		cm.On("Modules", appMock, "").Return(modules, nil)

		return cm
	}

	cannotFindModules := func(appMock *amocks.App) component.Manager {
		cm := &cmocks.Manager{}

		cm.On("Modules", appMock, "").Return(nil, errors.New("fail"))

		return cm
	}

	cases := []struct {
		name             string
		outputType       string
		outputName       string
		componentManager func(a *amocks.App) component.Manager
		isErr            bool
	}{
		{
			name:             "output table",
			outputType:       "table",
			outputName:       "module/list/output.txt",
			componentManager: validComponentManager,
		},
		{
			name:             "output table",
			outputType:       "json",
			outputName:       "module/list/output.json",
			componentManager: validComponentManager,
		},
		{
			name:             "invalid output format",
			outputType:       "invalid",
			componentManager: validComponentManager,
			isErr:            true,
		},
		{
			name:             "invalid output format",
			outputType:       "invalid",
			componentManager: cannotFindModules,
			isErr:            true,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			withApp(t, func(appMock *amocks.App) {

				in := map[string]interface{}{
					OptionApp:     appMock,
					OptionEnvName: "",
					OptionOutput:  tc.outputType,
				}

				a, err := NewModuleList(in)
				require.NoError(t, err)

				a.cm = tc.componentManager(appMock)

				var buf bytes.Buffer
				a.out = &buf

				err = a.Run()
				if tc.isErr {
					require.Error(t, err)
					return
				}
				require.NoError(t, err)

				assertOutput(t, tc.outputName, buf.String())
			})
		})
	}

}

func TestModuleList_requires_app(t *testing.T) {
	in := make(map[string]interface{})
	_, err := NewModuleList(in)
	require.Error(t, err)
}
